/**
 * BM98 螺旋矩阵
 */

/**
 * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
 *
 * @param matrix int整型二维数组
 * @return int整型一维数组
 */
export function spiralOrder(matrix: number[][]): number[] {
  // write code here
  let result: number[] = [];
  let rowStart = 0;
  let rowEnd = matrix.length - 1;
  let colStart = 0;
  let colEnd = matrix.length > 0 ? matrix[0].length - 1 : 0;
  let colForward = true;
  let rowForward = true;
  let total = matrix.length * (matrix.length > 0 ? matrix[0].length : 0);
  // 遍历行
  while (result.length !== total) {
    // console.log(rowStart, rowEnd, colStart, colEnd);

    if (rowForward) {
      result = result.concat(matrix[rowStart].slice(colStart, colEnd + 1));
      rowStart++;
    } else {
      result = result.concat(
        matrix[rowEnd].slice(colStart, colEnd + 1).reverse()
      );
      rowEnd--;
    }
    // 反转
    rowForward = !rowForward;

    // 遍历列
    if (colForward) {
      for (let index = rowStart; index <= rowEnd; index++) {
        result.push(matrix[index][colEnd]);
      }
    } else {
      for (let index = rowEnd; index >= rowStart; index--) {
        result.push(matrix[index][colStart]);
      }
    }
    if (colForward) {
      colEnd--;
    } else {
      colStart++;
    }
    // 反转
    colForward = !colForward;

    // console.log(result);
  }
  return result;
}

console.log(
  spiralOrder([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
  ])
);
